package com.baizhi.shiro.config;


import com.baizhi.shiro.realm.AuthenRealm;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

@Configuration
public class ShiroConfig {

    /**
     * @author cyf碎碎恋
     *
     *      shiro 的配置类：主要做两件事
     *      一：创建过滤工厂，配置过滤信息
     *      二：创建安全管理器，并将我们自己写的Realm 以形参传入
     *
     */

    Logger logger = LoggerFactory.getLogger(ShiroConfig.class);

    /**
     * 创建过滤工厂，并进行配置过滤器
     */

    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(DefaultWebSecurityManager securityManager){
        logger.info("过滤工厂启动，过滤请求");
        /**
         * 设置拦截规则
         *  anon 匿名可访问  不需要认证就可以访问
         *  authc  认证可访问  需要认证通过才能访问
         *
         */
        ShiroFilterFactoryBean filterFactoryBean = new ShiroFilterFactoryBean();
        Map map = new HashMap();
        map.put("/login.jsp","authc");
        map.put("/admin/*","anon");
        map.put("/jsp/*","authc");
        map.put("/main.jsp","authc");
        map.put("/guru/*","authc");
        map.put("/article/*","authc");
        map.put("/user/*","authc");
        //map.put("/menu/**","anon");

        filterFactoryBean.setFilterChainDefinitionMap(map);
        filterFactoryBean.setSecurityManager(securityManager);

        return filterFactoryBean;
    }


    /**
     * 创建安全管理器，并导入我们的查询数据库Realm
     *
     */
    @Bean
    public DefaultWebSecurityManager defaultWebSecurityManager(AuthenRealm authenRealm ){
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();

        // 设置自定义Realm
        securityManager.setRealm(authenRealm);
        return securityManager;
    }


    @Bean
    public AuthenRealm authenRealm(){
        return new AuthenRealm();
    }
}
